﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Fluent;
using System.Windows.Markup;
using Microsoft.Win32;
using System.IO;
using OrganizeYourSearch.Helpers;

namespace OrganizeYourSearch
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : RibbonWindow
    {

        public MainWindow()
        {
            InitializeComponent();
            
        }

        private void RibbonWindow_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeRibbonComponents();
            this.AddHandler(CloseableTabItem.CloseTabEvent, new RoutedEventHandler(this.CloseTab));
            this.AddNewTab.MouseLeftButtonUp += new MouseButtonEventHandler(AddNewTab_MouseLeftButtonUp);
        }


        private void InitializeRibbonComponents()
        {
            
            //Filling Fonts in the ComboBox
            //int i;
            //foreach (FontFamily fontFamily in Fonts.SystemFontFamilies)
            //{
            //    cbFontFace.Items.Add(fontFamily.Source);
            //}
            //cbFontFace.SelectedItem = "Times New Roman";
            //cbFontFace.IsTextSearchEnabled = true;
            

            ////FontFace.SelectedIndex = 0;

            ////Filling FontSize in the ComboBox
            //i = 8;
            //while (i < 12)
            //    cbFontSize.Items.Add(i++);
            //while (i < 28)
            //{
            //    cbFontSize.Items.Add(i);
            //    i += 2;
            //}
            //int j = 4;
            //while (i < 72)
            //{
            //    cbFontSize.Items.Add(i);
            //    i += j;
            //    j += j;
            //}
            //cbFontSize.SelectedIndex = 8;
           

        }




        /// <summary>
        /// When the AddNewTab Button is clicked, the following activities happen:
        /// 1) Create a new flow document, add it to RichTextBox and add the RichTextBox as the content of 
        ///    newTabItem. Remember, we have enabled the acceptsTab feature of the RichTextBox
        /// 2) The adderTabItem (ie the AddNewTab Button) is removed from the DocTabControl and newTabItem is 
        ///    placed in its place.
        /// 3) Focus is set to newTabItem.
        /// 4) Finally the adderTabItem is again added to the DocTabControl so that it again appears at the end
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private Color ColorFromHexValue(string hexColor)
        {
            Color c = Color.FromArgb(
                        Convert.ToByte(hexColor.Substring(1, 2), 16),
                        Convert.ToByte(hexColor.Substring(3, 2), 16),
                        Convert.ToByte(hexColor.Substring(5, 2), 16),
                        Convert.ToByte(hexColor.Substring(7, 2), 16)
                    );
            return c;
        }
        /// <summary>
        /// Adds up a new tab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void AddNewTab_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            // see if actually the AddNewTab button is pressed, or is the event triggered by any content
            // inside the tab, and it only got routed up to this tab. If the source is same as the sender,
            // then, the event is raised by clicking the addnewtab button. So, you can proceed, else just ignore.
            if (e.Source.GetType() == sender.GetType())
            {
                CloseableTabItem newTabItem = new CloseableTabItem();
                CloseableTabItem adderTabItem = AddNewTab;
                if (adderTabItem != null)
                {
                    FlowDocument flow = new FlowDocument();
                    RichTextBox rTextBox = new RichTextBox(flow);
                    Grid bgpanel = new Grid();
                    bgpanel.Background = new SolidColorBrush(ColorFromHexValue("#FFB1B1DA"));
                    rTextBox.AcceptsTab = true;
                    rTextBox.Width = 1015;
                    rTextBox.Margin = new Thickness(0, 20, 0, 0);
                    rTextBox.HorizontalAlignment = HorizontalAlignment.Center;
                    //rTextBox.SpellCheck.IsEnabled = true;
                    rTextBox.Document.PageHeight = 11 * 96;
                    rTextBox.Document.PageWidth = 8.4 * 96;
                    rTextBox.Document.FontSize = 14.0;
                    rTextBox.Document.TextAlignment = TextAlignment.Justify;
                    rTextBox.Padding = new Thickness(85, 55, 15, 5);
                    bgpanel.Children.Add(rTextBox);

                    newTabItem.Content = bgpanel;
                    DocTabControl.Items.Remove(adderTabItem);
                    DocTabControl.Items.Add(newTabItem);
                    newTabItem.Focus();

                    DocTabControl.Items.Add(adderTabItem);
                }// end inner if
                else
                    MessageBox.Show("Argument returned null");
            }// end outer if
           
        }

        /// <summary>
        /// Creates a new ClosableTabItem, adds a richtextbox to it, sets standard values to it, and adds
        /// document contents provided by the command line parameters provided as array of string
        /// CALLED BY: OnStartupNextInstance() in Startup.cs 
        /// </summary>
        /// <param name="str">Commandline parameters which represent document content and URL</param>
        public void Method_AddNewTab(string[] str)
        {
            CloseableTabItem newTabItem = new CloseableTabItem();
            CloseableTabItem adderTabItem = AddNewTab;
            if (adderTabItem != null)
            {
                FlowDocument flow;
                flow=GetFlowDocWithContents(str);
                Grid bgpanel = new Grid();
                bgpanel.Background = new SolidColorBrush(ColorFromHexValue("#FFB1B1DA"));
                RichTextBox rTextBox = new RichTextBox(flow);
                rTextBox.AcceptsTab = true;
                
                rTextBox.Width = 1015;
                rTextBox.Margin = new Thickness(0, 20, 0, 0);
                rTextBox.HorizontalAlignment = HorizontalAlignment.Center;
                //rTextBox.SpellCheck.IsEnabled = true;
                rTextBox.Document.PageHeight = 11*96;
                rTextBox.Document.PageWidth = 8.4*96;
                rTextBox.Document.FontSize = 14.0;
                rTextBox.Document.TextAlignment = TextAlignment.Justify;
                rTextBox.Padding = new Thickness(75, 55, 15, 5);

                bgpanel.Children.Add(rTextBox);
                newTabItem.Content = bgpanel;
                DocTabControl.Items.Remove(adderTabItem);
                DocTabControl.Items.Add(newTabItem);
                newTabItem.Focus();
               
                DocTabControl.Items.Add(adderTabItem);
            }
            else
                MessageBox.Show("Argument returned null");
        }

        /// <summary>
        /// Function to add the content sent from the Webpage to the flowdocument. It also adds the url of the page.
        /// Called From: Method_AddNewItem(string[] str)
        /// </summary>
        /// <param name="str">Commandline parameters which represent document content and URL</param>
        /// <returns>flowDocument</returns>
        FlowDocument GetFlowDocWithContents(string[] str)
        {
            FlowDocument flow = new FlowDocument();
            //Add the copied text content to the flowdocument
            if (!string.IsNullOrEmpty(str[0]))
            {
                Paragraph para1 = new Paragraph(); 
                Run run1 = new Run();
                run1.Text = str[0];
                para1.Inlines.Add(run1);
                para1.Inlines.Add(new LineBreak());
                flow.Blocks.Add(para1);

                //Add the URL of the source to the flowdocument
                if (!string.IsNullOrEmpty(str[1]))
                {
                    Paragraph para2 = new Paragraph();
                    Hyperlink url = new Hyperlink();
                    Run hyperRun = new Run();
                    hyperRun.Text = str[1];
                    url.Inlines.Add(hyperRun);
                    para2.Inlines.Add(url);

                    Run datetime=new Run();
                    datetime.Text=System.DateTime.Now.ToString();
                    para2.Inlines.Add(new LineBreak());
                    para2.Inlines.Add(datetime);
                    flow.Blocks.Add(para2);

                }

                // Add the DateTime info of the document creation
                
            }
            
            return flow;
        }

        /// <summary>
        /// This event is triggered when the cross button in any tabItem is clicked. It closes the tabItem
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>

        private void CloseTab(object source, RoutedEventArgs args)
        {
            // If it is a DocReader with annotatoin, flush Annotations to file.
            DocContainerClosableTabItem readerTabItem = args.Source as DocContainerClosableTabItem;
            if (readerTabItem != null)
            {
                readerTabItem.FlushAnnoattionsToFile();
            }

            TabItem tabItem = args.Source as TabItem;
            if (tabItem != null)
            {
                TabControl tabControl = tabItem.Parent as TabControl;
                if (tabControl != null)
                    tabControl.Items.Remove(tabItem);
                
            }
        }

        private void SaveBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
              e.Handled=true;
        }

        /// <summary>
        /// Function to save the file when ctrl+s or file > save button is hit.
        /// It finds the selected dockpanel and the richtextbox contained in it. Then, displaying the dialog box, it saves.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {  
            try
            {
                Grid parentGrid= DocTabControl.SelectedContent as Grid;
                RichTextBox richTextBox;
                foreach(UIElement ui in parentGrid.Children)
                {
                    if (ui.GetType() == typeof(RichTextBox))
                    {
                        richTextBox = ui as RichTextBox;
                        System.Windows.Forms.SaveFileDialog saveFile = new System.Windows.Forms.SaveFileDialog();
                        saveFile.Filter = "XAML Files (*.xaml)|*.xaml";
                        string dirPath="C:\\Users\\Samant\\Documents\\OYS\\";
                        if(Directory.Exists(dirPath))
                            saveFile.InitialDirectory = dirPath;
                        
                        System.Windows.Forms.DialogResult result = saveFile.ShowDialog();
                        if (result==System.Windows.Forms.DialogResult.OK)
                        {
                              
                            string filenameWithExtension = FileNameHelper.GetFileNameOnlyWithExtension(saveFile.FileName);
                            string fullpath = saveFile.FileName;
                            string pathWithoutExtension = FileNameHelper.RemoveExension(fullpath);

                           
                            // Create the subfolder ..\OYS\filename\
                            System.IO.Directory.CreateDirectory(pathWithoutExtension);

                            //Combine the filename to the new directory path. ie make ..\OYS\filename\filename.xaml
                            saveFile.FileName = System.IO.Path.Combine(pathWithoutExtension, filenameWithExtension);

                            // Create a TextRange around the entire document.
                            TextRange documentTextRange = new TextRange(
                            richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
                            // If this file exists, it's overwritten.
                            using (FileStream fs = File.Create(saveFile.FileName))
                            {
                                if (System.IO.Path.GetExtension(saveFile.FileName).ToLower() == ".rtf")
                                {
                                    documentTextRange.Save(fs, DataFormats.Rtf);
                                }
                                else
                                {
                                    documentTextRange.Save(fs, DataFormats.Xaml);
                                    //documentTextRange.Save(fs,DataFormats.XamlPackage);
                                }
                            }
                        }//end if(savefile)

                        break;
                    } // end foreach UI Element
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in saving file.\n" + ex.Message);
            }
            finally
            {
                e.Handled = true;
            }

        }

        private void OpenBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
            e.Handled = true;

           
        }

        // 1) Make an instance of CloseableTabItem
        // 2) Give the open file dialog box and load the document as the document content of the doc pageviewer
        // 3) Add vertTabControl (for bookmarks etc list) and doc page viewer to the CloseableTabItem (ie newTabItem)
        // 4) Add newTabItem to the main tab control and set focus to it.
        private void OpenBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            { 
                CloseableTabItem adderTabItem = AddNewTab;
                if (adderTabItem != null)
                {
                    FlowDocument flow = new FlowDocument();
                    FlowDocumentPageViewer viewer = new FlowDocumentPageViewer();
                    flow.PagePadding = new Thickness(75, 55, 20, 10);
                    flow.TextAlignment = TextAlignment.Justify;
                    flow.Background = new SolidColorBrush(Colors.White);

                    System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
                   
                    openFile.Filter = "XAML Files (*.xaml)|*.xaml";

                    string dirPath = "C:\\Users\\Samant\\Documents\\OYS\\";
                    openFile.RestoreDirectory = true;

                    if (Directory.Exists(dirPath))
                        openFile.InitialDirectory = dirPath;
                        
                    else
                        openFile.InitialDirectory = System.Environment.SpecialFolder.MyDocuments.ToString();
                    System.Windows.Forms.DialogResult result = openFile.ShowDialog();
                     if(result==System.Windows.Forms.DialogResult.OK)
                    {
                       TextRange docTextRange=new TextRange(flow.ContentStart,flow.ContentEnd);
                        using (FileStream fs = File.Open(openFile.FileName, FileMode.Open))
                        {
                            try
                            {
                                docTextRange.Load(fs, DataFormats.Xaml);
                                flow.ColumnWidth = 7.0 * 96;
                                // Set the openend document as the FlowDocumentPageViewer's document

                                viewer.Document = flow;
                                viewer.Document.DocumentPaginator.PageSize = new Size(8.4 * 96, 11 * 96);
                                viewer.Padding = new Thickness(35, 55, 15, 5);

                                //vertTabCtrl.Width = 300;

                                // Set the dockpanel as the content of the newTabItem
                                DocContainerClosableTabItem newTabItem = new DocContainerClosableTabItem(viewer,openFile.FileName);

                                // Rearrange the occurance of the NewTabItem and adderTabItem and set focus to the newTabItem
                                DocTabControl.Items.Remove(adderTabItem);
                                DocTabControl.Items.Add(newTabItem);
                                DocTabControl.Items.Add(adderTabItem);
                                newTabItem.Focus();
                            }
                            catch (XamlParseException ex)
                            {
                                MessageBox.Show("Sorry, problem"+ex);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("General Ex"+ex);
                            }
                        }
                        
                    } 
                }
                else
                    MessageBox.Show("Open File Error: Argument returned null in creating a new Tab");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in opening file.\n" + ex.Message);
            }
            finally
            {
                e.Handled = true;
            }
        }

        public void OpenFileFromGivenPath(string fileName)
        {
           try
            {
                CloseableTabItem adderTabItem = AddNewTab;
                if (adderTabItem != null)
                {
                    FlowDocument flow = new FlowDocument();
                    FlowDocumentPageViewer viewer = new FlowDocumentPageViewer();
                    flow.PagePadding = new Thickness(75, 55, 20, 10);
                    flow.TextAlignment = TextAlignment.Justify;
                    flow.Background = new SolidColorBrush(Colors.White);

                    TextRange docTextRange = new TextRange(flow.ContentStart, flow.ContentEnd);
                    using (FileStream fs = File.Open(fileName, FileMode.Open))
                    {
                        try
                        {
                            docTextRange.Load(fs, DataFormats.Xaml);
                            flow.ColumnWidth = 7.0 * 96;
                            // Set the openend document as the FlowDocumentPageViewer's document

                            viewer.Document = flow;
                            viewer.Document.DocumentPaginator.PageSize = new Size(8.4 * 96, 11 * 96);
                            viewer.Padding = new Thickness(35, 55, 15, 5);

                            //vertTabCtrl.Width = 300;

                            // Set the dockpanel as the content of the newTabItem
                            DocContainerClosableTabItem newTabItem = new DocContainerClosableTabItem(viewer, 
                                fileName);

                            // Rearrange the occurance of the NewTabItem and adderTabItem and set focus to the
                            //newTabItem
                            DocTabControl.Items.Remove(adderTabItem);
                            DocTabControl.Items.Add(newTabItem);
                            DocTabControl.Items.Add(adderTabItem);
                            newTabItem.Focus();
                        }
                        catch (XamlParseException ex)
                        {
                            MessageBox.Show("Sorry, problem" + ex);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("General Ex" + ex);
                        }
                    }// end using

                }// end if

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in opening file.\n" + ex.Message);
            }
            finally
            {
                
            }
       }
        private void OpenBrowser_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
            e.Handled = true;
        }

        private void OpenBrowser_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                CloseableTabItem newTabItem = new CloseableTabItem();
                CloseableTabItem adderTabItem = AddNewTab;
                if (adderTabItem != null)
                {
                    WebBrowserControl wbc = new WebBrowserControl();
                    newTabItem.Content = wbc;
                    DocTabControl.Items.Add(newTabItem);
                    DocTabControl.Items.Remove(adderTabItem);
                    DocTabControl.Items.Add(adderTabItem);
                    newTabItem.Focus();
                }
                else
                    MessageBox.Show("Argument returned null");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception in opening browser control." + ex.Message);
            }
            finally
            {
                e.Handled = true;
            }
        }

        private void NewBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
            e.Handled = true;
        }
        private void NewBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Method_AddNewTab(new string[]{"",""});
        }

    }   
}

